
/**
 * Sencha GXT 3.1.0 - Sencha for GWT
 * Copyright(c) 2007-2014, Sencha, Inc.
 * licensing@sencha.com
 *
 * http://www.sencha.com/products/gxt/license/
 */
package com.jp.app.client;
 
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
import com.jp.app.client.GXT.images.ExampleImages;
import com.jp.app.client.model.Book;
import com.jp.app.client.model.BookProperties;
import com.jp.app.client.model.RecordResult;
import com.sencha.gxt.core.client.GXT;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.state.client.CookieProvider;
import com.sencha.gxt.state.client.GridStateHandler;
import com.sencha.gxt.state.client.StateManager;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Resizable;
import com.sencha.gxt.widget.core.client.Resizable.Dir;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.button.ToolButton;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.CollapseEvent;
import com.sencha.gxt.widget.core.client.event.CollapseEvent.CollapseHandler;
import com.sencha.gxt.widget.core.client.event.ExpandEvent;
import com.sencha.gxt.widget.core.client.event.ExpandEvent.ExpandHandler;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.form.FieldLabel;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.tips.QuickTip;
import com.sencha.gxt.widget.core.client.tips.ToolTipConfig;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
 
public class Test implements IsWidget, EntryPoint {
 
  private static final BookProperties props = GWT.create(BookProperties.class);
 
  private ContentPanel root;
  private Window formWindow;
  private TextField title;
  private TextField author;
  
  private Grid<Book> grid;
  private ListStore<Book> store;
  private RequestBuilder getBooksReq;
  private RequestBuilder saveBooksReq;
  private BookAutoBeanFactory factory;
  
  public interface BookAutoBeanFactory extends AutoBeanFactory {
	    AutoBean<RecordResult> items();
   }
      
  @Override
  public Widget asWidget() {
    if (root == null) {
    	
      factory = GWT.create(BookAutoBeanFactory.class);	
    	
      createRequests();
      createForm();
      
      ColumnConfig<Book, String> titleCol = new ColumnConfig<Book, String>(props.title(), 50, SafeHtmlUtils.fromTrustedString("<b>Title</b>"));
      ColumnConfig<Book, String> authorCol = new ColumnConfig<Book, String>(props.author(), 100, "Author");
 
      List<ColumnConfig<Book, ?>> l = new ArrayList<ColumnConfig<Book, ?>>();
      l.add(titleCol);
      l.add(authorCol);
      ColumnModel<Book> cm = new ColumnModel<Book>(l);
 
      store = new ListStore<Book>(props.key());
 
      root = new ContentPanel();
      root.setHeadingText("Basic Grid");
      root.getHeader().setIcon(ExampleImages.INSTANCE.table());
      root.setPixelSize(600, 300);
      root.addStyleName("margin-10");
       
      ToolButton info = new ToolButton(ToolButton.QUESTION);
      ToolTipConfig config = new ToolTipConfig("Example Info", "This examples includes resizable panel, reorderable columns and grid state.");
      config.setMaxWidth(225);
      info.setToolTipConfig(config);
      root.addTool(info);
       
      final Resizable resizable = new Resizable(root, Dir.E, Dir.SE, Dir.S);
      root.addExpandHandler(new ExpandHandler() {
        @Override
        public void onExpand(ExpandEvent event) {
          resizable.setEnabled(true);
        }
      });
      root.addCollapseHandler(new CollapseHandler() {
        @Override
        public void onCollapse(CollapseEvent event) {
          resizable.setEnabled(false);
        }
      });
 
      grid = new Grid<Book>(store, cm);
      grid.getView().setAutoExpandColumn(titleCol);
      grid.getView().setStripeRows(true);
      grid.getView().setColumnLines(true);
      grid.setBorders(false);
 
      grid.setColumnReordering(true);
      grid.setStateful(true);
      grid.setStateId("gridExample");
 
      GridStateHandler<Book> state = new GridStateHandler<Book>(grid);
      state.loadState();
 
      ToolBar toolBar = new ToolBar();
      toolBar.setEnableOverflow(false);
      
      TextButton saveBooksBtn = new TextButton("Create Book", new SelectHandler() {

          @Override
          public void onSelect(SelectEvent event) {
        	  formWindow.show();
          }}
        );
      
      toolBar.add(saveBooksBtn);
      
      VerticalLayoutContainer con = new VerticalLayoutContainer();
      root.setWidget(con);
 
      con.add(toolBar, new VerticalLayoutData(1, -1));
      con.add(grid, new VerticalLayoutData(1, 1));
 
      // needed to enable quicktips (qtitle for the heading and qtip for the
      // content) that are setup in the change GridCellRenderer
      new QuickTip(grid);
    }
 
    return root;
  }
  
  private void createForm() {
	    ContentPanel panel = new ContentPanel();
	    panel.setHeaderVisible(false);
	    panel.setWidth(350);
	 
	    VerticalLayoutContainer p = new VerticalLayoutContainer();
	    panel.add(p);
	 
	    title = new TextField();
	    title.setAllowBlank(false);
	    title.setEmptyText("Enter the title...");
	    p.add(new FieldLabel(title, "Title"), new VerticalLayoutData(1, -1));
	 
	    author = new TextField();
	    author.setAllowBlank(false);
	    p.add(new FieldLabel(author, "Author"), new VerticalLayoutData(1, -1));
	 	  
	    TextButton saveBtn = new TextButton("Save", new SelectHandler(){
			@Override
			public void onSelect(SelectEvent event) {
	        	  StringBuilder sb = new StringBuilder();
	        	  sb.append(createNamePairValue("title",title.getValue())).append("&");
	        	  sb.append(createNamePairValue("author",author.getValue()));
	        	  saveBooksReq.setRequestData(sb.toString());
	        	  
	        	  saveBooksReq.setCallback(new RequestCallback() {
	          		@Override
	          		public void onResponseReceived(Request request, Response response) {
	          			title.clear();
	          			author.clear();
	          			formWindow.hide();
	          			getBooks();
	          		}
	          		@Override
	          		public void onError(Request request,	Throwable exception) {
	          			// TODO Auto-generated method stub
	          		}
	          	         
	          	    });
				
	        	  try {
	        		  saveBooksReq.send();
	        	    }
	        	  catch (Exception e){
	        	       e.printStackTrace();
	        	    }
	        	  
			}} );
	    
	    
	    TextButton cancelBtn = new TextButton("Cancel", new SelectHandler(){
			@Override
			public void onSelect(SelectEvent event) {
      			title.clear();
      			author.clear();
				formWindow.hide();
			}});
	    
	    panel.addButton(saveBtn);
	    panel.addButton(cancelBtn);
	 
	    formWindow = new Window();
	    formWindow.setModal(true);
	    formWindow.add(panel);
	  }
  
  private void createRequests(){
	  getBooksReq = new RequestBuilder(RequestBuilder.GET, "/book/getBooks.json");
	  
	  saveBooksReq = new RequestBuilder(RequestBuilder.POST, "/book/create-book.json");
	  saveBooksReq.setHeader("Content-Type","application/x-www-form-urlencoded");
	  getBooks();
  }
   
  private void getBooks(){
	  getBooksReq.setCallback(new RequestCallback() {

  		@Override
  		public void onResponseReceived(Request request, Response response) {
  			RecordResult result = null;
  			if(response.getText() != null){
  				AutoBean<RecordResult> bean = AutoBeanCodex.decode(factory, RecordResult.class, response.getText());
  				result = bean.as();
  				store.clear();
  				store.addAll(result.getRecords());
  			}
  			
  		}

  		@Override
  		public void onError(Request request,	Throwable exception) {
  			// TODO Auto-generated method stub
  		}
  	         
  	    });
  	  
  	  try {
  		  getBooksReq.send();
  	    }
  	  catch (Exception e){
  	       e.printStackTrace();
  	    }
	  
  }
  
  private String createNamePairValue(String title, String value){
	  StringBuilder sb = new StringBuilder();
	  sb.append(URL.encode(title)).append("=").append(URL.encode(value));
	  return sb.toString();
  }
  
  @Override
  public void onModuleLoad() {
    StateManager.get().setProvider(new CookieProvider("/", null, null, GXT.isSecure()));
    RootPanel.get().add(asWidget());
  }
}